﻿//===============================================================================
// SharePoint911 - http://www.SharePoint911.com
// SharePoint ActiveX Override (SPAXO)
// Created By: Larry J. Riemann
//===============================================================================
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
// POSSIBILITY OF SUCH DAMAGE.
//===============================================================================

using System;
using System.Web;
using SharePoint911.SPAXO.Properties;
using SharePoint911.SPAXO.Logging;
using System.Reflection;
using System.Web.Caching;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;

namespace SharePoint911.SPAXO
{
    /// <summary>
    /// Http Module used to inject javascript into SharePoint pages to override certain ActiveX issues
    /// </summary>
    public sealed class ActiveXOverrideModule : IHttpModule
    {
        #region IHttpModule Members

        /// <summary>
        /// Disposes unmanaged resources of the module
        /// </summary>
        void IHttpModule.Dispose()
        {
            // Nothing to dispose
        }

        /// <summary>
        /// Initialize module settings
        /// </summary>
        /// <param name="application"></param>
        void IHttpModule.Init(HttpApplication application)
        {
            // Wireup Release Request State event to enable altering the response
            application.ReleaseRequestState += new EventHandler(application_ReleaseRequestState);
        }

        #endregion

        #region Application Events

        /// <summary>
        /// Handles the Release Request State event of the HttpApplication and modifies the response
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void application_ReleaseRequestState(object sender, EventArgs e)
        {
            try
            {
                // Get reference to the HttpApplication
                HttpApplication application = sender as HttpApplication;

                // Ceck to see if the application value is not null
                if (application != null)
                {
                    // If the applicaiton value is not null

                    // Get the absolute path of the request
                    string absolutePath = application.Request.Url.AbsolutePath;

                    if (absolutePath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase))
                    {
                        // Get a refernce to the response
                        HttpResponse response = application.Response;

                        // Check to see if the response is of a content type we should try to modify
                        if (response.ContentType.StartsWith("text/html", StringComparison.OrdinalIgnoreCase))
                        {
                            // Check to see if the module has been configured to inject the javascript into the head section
                            // Default is true
                            if (GetSettings().IsInjectToHeadSection)
                            {
                                // If the module has been configured to inject the javascript into the 
                                // head section specify the filterstream that will do the work
                                // NOTE: This option may cause issues if the literal that is used as the 
                                //       seach term (in this case </HEAD>) is found before the intetended term,
                                //       it could be found in comments, script or elsewhere
                                //       ** You should test thoroughly before using **
                                response.Filter = new InsertContentFilterStream(response.Filter, response.ContentEncoding, "</HEAD>", Resources.JavaScriptTag);
                            }
                            else
                            {
                                // Otherwise append the javascript to the end of the response
                                response.Write(Resources.JavaScriptTag);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Log exception in the case of failure
                using (UlsLogWriter logger = new UlsLogWriter())
                {
                    logger.Write(TraceProvider.TraceSeverity.CriticalEvent, Resources.UnhandledCategory, ex.ToString());
                }

                throw;
            }
        }

        #endregion

        #region Private Methods

        private static ConfigSettings GetSettings()
        {
            const string SPAXO_CACHE = "SPAXO_CACHE_KEY";

            Cache cache = HttpContext.Current.Cache;

            ConfigSettings settings = cache[SPAXO_CACHE] as ConfigSettings;

            if (settings == null)
            {
                settings = SpaxoGlobal.GetSettings(SPContext.Current.Site.WebApplication);

                if (settings == null)
                {
                    settings = SpaxoGlobal.CreateSettings(SPContext.Current.Site.WebApplication);
                    settings.InjectionOption = "Head";
                }

                cache.Add(SPAXO_CACHE, settings, null, DateTime.Now.Add(new TimeSpan(0, 5, 0)), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }

            return settings;
        }

        #endregion
    }
}
